package com.his.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.his.annotation.EnableEncryption;
import com.his.common.Rsp;
import com.his.utils.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 响应数据加密类
 */
@Slf4j
@ControllerAdvice(basePackages = "com.his.controller")
public class EncryptResponse implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {
            EnableEncryption enableRSA = parameter.getMethodAnnotation(EnableEncryption.class);
            //判断是否需要解密
            if (enableRSA!=null) {
                log.info("对方法method :【" + parameter.getMethod().getName() + "】返回数据进行加密");
                //只对rsp响应数据中的data加密
                Rsp rsp = (Rsp) body;
                Object data = rsp.getContent();
                //执行参数加密工作,先将返回的数据解析成Json字符串
                String value = new ObjectMapper().writeValueAsString(data);
                //加密
                String enCode = RsaUtils.encrypt(value);
                //设置返回响应头告诉前端数据加密了
                response.getHeaders().add("encode","true");
                rsp.setContent(enCode);
                return rsp;
            }else{
                return body;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("对方法method :【" + parameter.getMethod().getName() + "】返回数据进行解密出现异常："+e.getMessage());
            return body;
        }
    }
}
